<template>
  <div class="article-container">
    <!-- 分类/标签标题 -->
    <div v-if="categoryName || tagName" class="category-header">
      <h2 v-if="route.name === 'Category'">
        <i class="fas fa-folder-open"></i> 分类：{{ categoryName }}
      </h2>
      <h2 v-else-if="route.name === 'Tag'">
        <i class="fas fa-tag"></i> 标签：{{ tagName }}
      </h2>
    </div>

    <!-- 加载状态 -->
    <Loading v-if="loading" />

    <!-- 文章列表内容 -->
    <template v-else>
      <!-- 有文章时显示列表 -->
      <div v-if="articleList.length > 0" class="article-list">
        <ArticleCard 
          v-for="article in articleList" 
          :key="article.id" 
          :article="article"
          class="article-item"
        />
      </div>

      <!-- 无文章时的纯文字提示 -->
      <div v-else class="empty-state">
        <p class="empty-text">暂无文章内容</p>
        <button class="reload-button" @click="fetchArticles">
          <i class="fas fa-sync-alt"></i> 重新加载
        </button>
      </div>

      <!-- 分页控件 -->
      <div v-if="articleList.length > 0" class="pagination-wrapper">
        <el-pagination
          background
          layout="prev, pager, next, jumper, total"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
          :hide-on-single-page="true"
        />
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { 
  getArticleCards, 
  getArticleListbytag,
  getArticleListbycategory
} from '@/api/article'
import Loading from '@/components/ui/Loading.vue'
import ArticleCard from '@/components/blog/ArticleCard.vue'

const route = useRoute()
const articleList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const categoryName = ref('')
const tagName = ref('')

// 从sessionStorage恢复分页状态
const restorePaginationState = () => {
  const savedState = sessionStorage.getItem('paginationState')
  if (savedState) {
    const { page, routeName, routeId } = JSON.parse(savedState)
    if (routeName === route.name && routeId === route.params.id) {
      currentPage.value = page
    }
  }
}

// 保存分页状态到sessionStorage
const savePaginationState = () => {
  sessionStorage.setItem('paginationState', JSON.stringify({
    page: currentPage.value,
    routeName: route.name,
    routeId: route.params.id
  }))
}

// 获取分类或标签名称
const fetchCategoryOrTagName = () => {
  if (route.name === 'Category') {
    categoryName.value = route.query.name || '未知分类'
    tagName.value = ''
  } else if (route.name === 'Tag') {
    tagName.value = route.query.name || '未知标签'
    categoryName.value = ''
  } else {
    categoryName.value = ''
    tagName.value = ''
  }
}

// 获取文章列表
const fetchArticles = async () => {
  try {
    
    loading.value = true
    let res
    
    if (route.name === 'Tag') {
      res = await getArticleListbytag(route.params.id, currentPage.value, pageSize.value)
    } else if (route.name === 'Category') {
      res = await getArticleListbycategory(route.params.id, currentPage.value, pageSize.value)
    } else {
      res = await getArticleCards(currentPage.value, pageSize.value)
    }
    console.log('获取到的文章列表:', res.data.list)
    console.log('第一个文章的ID:', res.data.list[0]?.id)
    if (res.code === 200) {
      articleList.value = [...(res.data.list || [])]
      total.value = res.data.total || 0
      
      if (currentPage.value > 1 && articleList.value.length === 0) {
        currentPage.value = 1
        await fetchArticles()
      }
    } else {
      console.error('获取文章列表失败:', res.message)
      articleList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    articleList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 页码变化处理
const handlePageChange = (page) => {
  currentPage.value = page
  savePaginationState()
  fetchArticles()
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 初始化加载
onMounted(() => {
  restorePaginationState()
  fetchCategoryOrTagName()
  fetchArticles()
})

// 监听路由参数变化
watch(
  () => route.params.id,
  (newId, oldId) => {
    if (newId !== oldId) {
      currentPage.value = 1
      fetchCategoryOrTagName()
      fetchArticles()
    }
  }
)

// 监听路由名称变化
watch(
  () => route.name,
  (newName, oldName) => {
    if (newName !== oldName) {
      currentPage.value = 1
      fetchCategoryOrTagName()
      fetchArticles()
    }
  }
)
</script>

<style scoped>
.article-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  min-height: 1050px;
  position: relative;
}

.category-header {
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.category-header h2 {
  color: #333;
  font-size: 1.8rem;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.category-header i {
  color: #409eff;
}

.article-list {
  display: flex;
  flex-direction: column;
  gap: 25px;
  margin-bottom: 30px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 20px;
  text-align: center;
  border: 1px dashed #eaeaea;
  border-radius: 8px;
  background-color: #fafafa;
}

.empty-text {
  font-size: 1.2rem;
  color: #666;
  margin-bottom: 20px;
}

.reload-button {
  padding: 10px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.reload-button:hover {
  background-color: #66b1ff;
  transform: translateY(-2px);
}

.reload-button i {
  font-size: 14px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .article-container {
    padding: 15px;
  }
  
  .category-header h2 {
    font-size: 1.5rem;
  }
  
  .article-list {
    gap: 15px;
  }
  
  .empty-text {
    font-size: 1rem;
  }
}

@media (max-width: 480px) {
  .article-container {
    padding: 10px;
  }
  
  .category-header h2 {
    font-size: 1.3rem;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
  }
  
  .empty-state {
    padding: 30px 15px;
  }
}
</style>